<template>
  <div class="draw-view">
    <div class="draw-container">
      <h1>Draw a Fish!</h1>
      <p class="subtitle">(facing right please)</p>

      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="color-palette">
          <button
            v-for="color in colors"
            :key="color"
            :style="{ backgroundColor: color }"
            :class="{ active: currentColor === color }"
            @click="selectColor(color)"
            :title="color"
          />
          <button
            class="eraser-btn"
            :class="{ active: isEraser }"
            @click="toggleEraser"
          >
            Eraser
          </button>
        </div>

        <div class="size-control">
          <label>Size:</label>
          <input
            v-model.number="brushSize"
            type="range"
            min="1"
            max="20"
            @input="updateBrushSize"
          />
          <span>{{ brushSize }}</span>
        </div>

        <div class="action-buttons">
          <button @click="undo" class="btn-undo">Undo</button>
          <button @click="clear" class="btn-clear">Clear</button>
          <button @click="flip" class="btn-flip">Flip</button>
        </div>
      </div>

      <!-- 画布 -->
      <canvas
        ref="canvas"
        class="drawing-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseout="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrawing"
      />

      <!-- 操作按钮 -->
      <div class="action-nav">
        <router-link to="/draw-a-fish/tank" class="btn-primary">
          tank
        </router-link>
        <button @click="submitFish" class="btn-submit">make it swim!</button>
        <router-link to="/draw-a-fish/rank" class="btn-primary">
          rank
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const canvas = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const currentColor = ref('#000000')
const isEraser = ref(false)
const brushSize = ref(6)
const history = ref([])

const colors = ['#000000', '#ff0000', '#00cc00', '#0000ff', '#ffff00', '#ff8800', '#ffffff']

onMounted(() => {
  const canvasEl = canvas.value
  canvasEl.width = 400
  canvasEl.height = 300
  ctx.value = canvasEl.getContext('2d')
  
  // 填充白色背景
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasEl.width, canvasEl.height)
  
  // 保存初始状态
  saveHistory()
})

const selectColor = (color) => {
  currentColor.value = color
  isEraser.value = false
}

const toggleEraser = () => {
  isEraser.value = !isEraser.value
}

const updateBrushSize = () => {
  // 更新笔刷大小
}

const startDrawing = (e) => {
  isDrawing.value = true
  const rect = canvas.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  
  ctx.value.beginPath()
  ctx.value.moveTo(x, y)
}

const draw = (e) => {
  if (!isDrawing.value) return
  
  const rect = canvas.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  
  ctx.value.lineWidth = brushSize.value
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
  
  if (isEraser.value) {
    ctx.value.clearRect(x - brushSize.value / 2, y - brushSize.value / 2, brushSize.value, brushSize.value)
  } else {
    ctx.value.strokeStyle = currentColor.value
    ctx.value.lineTo(x, y)
    ctx.value.stroke()
  }
}

const stopDrawing = () => {
  if (isDrawing.value) {
    isDrawing.value = false
    ctx.value.closePath()
    saveHistory()
  }
}

const handleTouchStart = (e) => {
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousedown', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  canvas.value.dispatchEvent(mouseEvent)
}

const handleTouchMove = (e) => {
  e.preventDefault()
  const touch = e.touches[0]
  const mouseEvent = new MouseEvent('mousemove', {
    clientX: touch.clientX,
    clientY: touch.clientY
  })
  canvas.value.dispatchEvent(mouseEvent)
}

const saveHistory = () => {
  history.value.push(canvas.value.toDataURL())
}

const undo = () => {
  if (history.value.length > 1) {
    history.value.pop()
    const imageData = history.value[history.value.length - 1]
    const img = new Image()
    img.onload = () => {
      ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
      ctx.value.drawImage(img, 0, 0)
    }
    img.src = imageData
  }
}

const clear = () => {
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height)
  history.value = []
  saveHistory()
}

const flip = () => {
  const imageData = ctx.value.getImageData(0, 0, canvas.value.width, canvas.value.height)
  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
  ctx.value.scale(-1, 1)
  ctx.value.drawImage(canvas.value, -canvas.value.width, 0)
  ctx.value.scale(-1, 1)
  saveHistory()
}

const submitFish = () => {
  const fishData = canvas.value.toDataURL()
  localStorage.setItem('lastFishDrawing', fishData)
  alert('鱼已保存！现在跳转到鱼缸...')
  router.push('/draw-a-fish/tank')
}
</script>

<style scoped>
.draw-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
}

.draw-container {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  max-width: 600px;
  width: 100%;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 5px;
}

.subtitle {
  text-align: center;
  color: #666;
  margin-bottom: 20px;
  font-size: 14px;
}

.toolbar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.color-palette {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.color-palette button {
  width: 40px;
  height: 40px;
  border: 3px solid transparent;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
}

.color-palette button.active {
  border-color: #333;
  transform: scale(1.1);
}

.color-palette button:hover {
  transform: scale(1.05);
}

.eraser-btn {
  padding: 8px 15px;
  background: #ddd;
  border: 2px solid transparent;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.eraser-btn.active {
  background: #999;
  color: white;
  border-color: #333;
}

.size-control {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.size-control input {
  flex: 1;
  max-width: 200px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons button {
  padding: 8px 15px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.action-buttons button:hover {
  background: #5568d3;
  transform: translateY(-2px);
}

.drawing-canvas {
  display: block;
  width: 100%;
  max-width: 400px;
  height: auto;
  border: 2px solid #ddd;
  border-radius: 8px;
  margin: 20px auto;
  background: white;
  cursor: crosshair;
}

.action-nav {
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
}

.btn-primary,
.btn-submit {
  padding: 12px 25px;
  border: none;
  border-radius: 5px;
  font-weight: bold;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  transition: all 0.3s;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5568d3;
  transform: translateY(-2px);
}

.btn-submit {
  background: #48bb78;
  color: white;
}

.btn-submit:hover {
  background: #38a169;
  transform: translateY(-2px);
}
</style>

